package cn.kailangtu.serialutils.modbus;

import java.util.Arrays;

public class ModbusRtuValidator {

    // 判断 byte[] 是否为完整 Modbus-RTU 帧
    public static boolean isCompleteModbusFrame(byte[] frame) {
        // 1. 检查数组非空且长度有效
        if (frame == null || frame.length < 4) {
            return false;
        }

        // 2. 提取数据和 CRC 校验码
        int dataLength = frame.length - 2;
        byte[] data = Arrays.copyOfRange(frame, 0, dataLength);
        int receivedCrc = ((frame[dataLength] & 0xFF) | ((frame[dataLength + 1] & 0xFF) << 8));

        // 3. 计算 CRC 并与接收值比较
        int calculatedCrc = calculateCRC(data);
        return calculatedCrc == receivedCrc;
    }

    // Modbus-RTU CRC 校验算法（参考实现）
    private static int calculateCRC(byte[] data) {
        int crc = 0xFFFF;
        for (byte b : data) {
            crc ^= (b & 0xFF);
            for (int i = 0; i < 8; i++) {
                if ((crc & 0x0001) != 0) {
                    crc = (crc >> 1) ^ 0xA001;
                } else {
                    crc >>= 1;
                }
            }
        }
        return crc;
    }
}

